import axios from 'axios'
import { getStorageToken } from './storage'

const service = axios.create({
	baseURL: import.meta.env.VITE_API_HOST,
	timeout: 5000,
})

service.interceptors.request.use(config => {
	if (getStorageToken()) {
		config.headers['Authorization'] = 'Bearer ' + getStorageToken()
	}
	return config
}, error => {
	return Promise.reject(error)
})

service.interceptors.response.use(response => {
	const { flag, msg } = response.data
	if (flag) {
		return response.data
	} else {
		window.$message.error(msg)
		return Promise.reject(new Error(msg))
	}
}, error => {
	window.$message.error(error.message)
	return Promise.reject(error)
})

export default service
